package cn.edu.njust.dao;

import cn.edu.njust.entity.Login;
import cn.edu.njust.util.JDBCUtils;

import java.sql.*;
import java.util.ArrayList;

public class UserDAOImpl implements UserDAO{
//    @Override
//    public ArrayList<Login> findAll() {
//        return null;
//    }

    @Override
    public Login findByName(String username) {        //根据username和查找用户
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();
            String sql = "select * from user where uName=?";        //SQL语句
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,username);
            rs = pstmt.executeQuery();
            if (rs.next()){
                Login user = new Login();
                user.setId(rs.getInt("uId"));
                user.setUsername(rs.getString("uName"));
                user.setPassword(rs.getString("uPw"));
                user.setSchool(rs.getString("uSchool"));
                user.setDepartment(rs.getString("uDepartment"));
                return user;
            }
            return null;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.close(rs,pstmt,conn);
        }
        return null;
    }

    @Override
    public Login findById(int id) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();
            String sql = "select * from user where uId=?";        //SQL语句
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1,id);
            rs = pstmt.executeQuery();
            if (rs.next()){
                Login user = new Login();
                user.setId(rs.getInt("uId"));
                user.setUsername(rs.getString("uName"));
                user.setPassword(rs.getString("uPw"));
                user.setSchool(rs.getString("uSchool"));
                user.setDepartment(rs.getString("uDepartment"));
                return user;
            }
            return null;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.close(rs,pstmt,conn);
        }
        return null;
    }
}
